package com.franklin.java.utils;

import com.franklin.java.api.classloader.ExternalJarsClassLoader;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.plugins.cl.PluginClassLoader;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;


/**
 * @author Franklin
 * @since 2021/9/16 15:42
 */
public class VirtualFileUtils {

    public static void deleteFile(@NotNull VirtualFile file) throws IOException {
        if (file.getParent() == null) {
            throw new IOException(IdeBundle.message("cannot.delete.root.directory", file.getPath()));
        }
        File ioFile = convertToIOFile(file);
        if (!FileUtil.delete(ioFile)) {
            throw new IOException(IdeBundle.message("delete.failed.error", ioFile.getPath()));
        }
    }

    public static @NotNull
    File convertToIOFile(@NotNull VirtualFile file) {
        return new File(toIoPath(file));
    }

    public static @NotNull
    String toIoPath(@NotNull VirtualFile file) {
        String path = file.getPath();
        if (StringUtil.endsWithChar(path, ':') && path.length() == 2 && SystemInfo.isWindows) {
            // makes 'C:' resolve to a root directory of the drive C:, not the current directory on that drive
            path += '/';
        }
        return path;
    }

    public static void loadJar(VirtualFile jarVirtualFile) {
        File jarFile = convertToIOFile(jarVirtualFile);
        URL url = null;
        try {
            url = jarFile.toURI().toURL();
            ExternalJarsClassLoader.loadJar(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}
